import Vue from 'vue';
import iView from 'iview';
import {router} from './router/index';
import {appRouter} from './router/router';
import store from './store';
import App from './app.vue';
import '@/locale';
import 'iview/dist/styles/iview.css';
import VueI18n from 'vue-i18n';
import util from './libs/util';

import crypto from 'crypto';

Vue.use(VueI18n);
Vue.use(iView);

// 请求拦截器  在数据请求之前将 token 数据加进去
util.ajax.interceptors.request.use(function (config) {
    let timestamp = new Date().getTime().toString();
    let content = timestamp + localStorage.token;
    let md5 = crypto.createHash('md5');
    md5.update(content);
    let randStr = md5.digest('hex');
    if (config.params) {
        config.params.rand_str = randStr;
        config.params.timestamp = timestamp;
        config.params.user_id = localStorage.user_id;
        config.params.company_id = localStorage.company_id;
        config.params.role_id = localStorage.role_id;
    } else {
        config['params'] = {
            rand_str: randStr,
            timestamp: timestamp,
            user_id: localStorage.user_id,
            company_id: localStorage.company_id,
            role_id: localStorage.role_id
        };
    }
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 响应拦截器   在数据响应之前，对数据进行操作
util.ajax.interceptors.response.use(function (response) {
    // code = 400 表示 token 值异常,跳转到登录页面重新登录
    if (response.data.code === 400) {
        app.$store.commit('logout', this);
        app.$store.commit('clearOpenedSubmenu');
        app.$router.push({
            name: 'login'
        });
    } else {
        return response;
    }
});

let app = new Vue({
    el: '#app',
    router: router,
    store: store,
    render: h => h(App),
    data: {
        currentPageName: ''
    },
    mounted () {
        this.currentPageName = this.$route.name;
        // 显示打开的页面的列表
        this.$store.commit('setOpenedList');
        this.$store.commit('initCachepage');
        // 权限菜单过滤相关
        // this.$store.commit('updateMenulist');
        // // iview-admin检查更新
        // util.checkUpdate(this);

        // 权限菜单过滤相关
        if (localStorage.token) {
            util.ajax.get('api/role/get_rules/' + localStorage.role_id).then(res => {
                if (res.data.code === 200) {
                    this.$store.commit('updateRulesList', res.data.data.rules_list);
                    this.$store.commit('updateMenulist');
                }
            });
        }
    },
    created () {
        let tagsList = [];
        appRouter.map((item) => {
            if (item.children.length <= 1) {
                tagsList.push(item.children[0]);
            } else {
                tagsList.push(...item.children);
            }
        });
        this.$store.commit('setTagsList', tagsList);
    }
});
